<template>
  <div>
    <!-- 查询条件表单 -->
    <el-form :inline="true" class="mb-4">
      <el-form-item label="编码">
        <el-input
          v-model="query.code"
          style="width: 200px"
          placeholder="请输入编码"
          clearable
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="query.status" placeholder="请选择状态" style="width: 160px" clearable>
          <el-option label="全部" :value="null" />
          <el-option label="待审核" :value="1" />
          <el-option label="已审核" :value="2" />
          <el-option label="已驳回" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="单据日期：">
        <el-date-picker
          v-model="query.dateRange"
          type="daterange"
          range-separator="至"
          :start-placeholder="query.dateRange[0] || '开始'"
          :end-placeholder="query.dateRange[1] || '结束'"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="fetchData(1)">查询</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 列表 -->
    <TestPage
      :table-data="tableData"
      :columns="columns"
      :current-page="pageNo"
      :total="total"
      :page-size="pageSize"
      @page-change="fetchData"
      @action="handleTableAction"
      @delete="handleDelete"
      @row-audit="openAudit"
    />

    <!-- 审核对话框 -->
    <el-dialog v-model="auditVisible" title="审核产品拆卸" width="500px">
      <el-form ref="auditFormRef" :model="auditForm" :rules="auditRules" label-width="100px">
        <el-form-item label="拆卸单号：" prop="code">
          <el-input v-model="auditForm.code" disabled />
        </el-form-item>
        <el-form-item label="审核人：" prop="auditor">
          <el-select v-model="auditForm.auditor" placeholder="请选择审核人" filterable clearable>
            <el-option
              v-for="u in userList"
              :key="u.id"
              :label="u.name"
              :value="u.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="审核结果：" prop="pass">
          <el-select v-model="auditForm.pass" placeholder="请选择结果">
            <el-option label="通过" :value="true" />
            <el-option label="不通过" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核意见：" prop="comment">
          <el-input type="textarea" v-model="auditForm.comment" rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="auditVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">提交审核</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/util/request'
import TestPage from '@/test/TestPage.vue'
import type { ProDivide } from '@/types/kc/CPCX'
import type { User } from '@/types/rs/User'
import { useRouter } from 'vue-router'
import type { OutStoreOrder, outStoreDetail } from '@/types/kc/outStore'
import type { InStoreOrder, InStoreDetail } from '@/types/kc/InStore'

// --- 分页 & 查询 ---
const pageNo = ref(1), pageSize = ref(5), total = ref(0)
const query = reactive<{ code: string; status: number|null; dateRange: [string,string]|[] }>({
  code: '', status: null, dateRange: []
})
const tableData = ref<ProDivide[]>([])

// --- 审核弹窗 ---
const auditVisible = ref(false)
const auditFormRef = ref()
const auditForm = reactive({ code: '', auditor: '', pass: null as boolean|null, comment: '' })
const auditRules = {
  auditor: [{ required: true, message: '请选择审核人', trigger: 'change' }],
  pass:    [{ required: true, message: '请选择结果',     trigger: 'change' }]
}
const userList = ref<User[]>([])
let currentRow: ProDivide|null = null

// --- 列定义 ---
const columns = [
  { prop:'id',     label:'ID' },
  { prop:'code',   label:'编码' },
  { prop:'bname',  label:'BOM名称' },
  { prop:'pname',  label:'产品名称' },
  { prop:'count',  label:'数量' },
  { prop:'status', label:'状态' },
  { prop:'date',   label:'日期' },
  { prop:'skname', label:'仓管人' },
  // … 其它字段 …
]

// --- 初始化 ---
onMounted(async () => {
  // 加载用户列表
  const r = await request.post('/per/user/getAll')
  userList.value = r.data.data
  fetchData(1)
})

// --- 工具：格式化日期区间 ---
function fmtDate(d: Date, end=false){
  const z=(n:number)=>n.toString().padStart(2,'0')
  const Y=d.getFullYear(), M=z(d.getMonth()+1), D=z(d.getDate())
  return end?`${Y}-${M}-${D} 23:59:59`:`${Y}-${M}-${D} 00:00:00`
}

// 编辑 & 删除
const router = useRouter()
async function handleDelete(row: ProDivide) {
  try {
    await ElMessageBox.confirm(
      '确定要删除该条记录吗？此操作不可恢复！',
      '警告',
      { type: 'warning' }
    )
    await request.post(
      'kc/proDivide/delProDivide',
      new URLSearchParams({ code: row.code }),
      { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
    )
    ElMessage.success('删除成功')
    fetchData(pageNo.value)
  } catch (err) {
    if (err === 'cancel') {
      ElMessage.info('已取消删除')
    } else {
      ElMessage.error('删除失败')
      console.error(err)
    }
  }
}
// 操作按钮
function handleTableAction(actionName: string) {
  if (actionName === 'add') {
    router.push({ name: 'Addcpzz' })
  }
}


// --- 拉取列表 ---
async function fetchData(p: number) {
  const ps = new URLSearchParams()
  ps.append('pageNow', `${p}`)
  ps.append('pageSize', `${pageSize.value}`)
  if (query.code)   ps.append('code', query.code)
  if (query.status!=null) ps.append('status', `${query.status}`)
  if (query.dateRange.length===2) {
    const [s,e] = query.dateRange.map(x=>new Date(x))
    ps.append('startDate', fmtDate(s,false))
    ps.append('endDate',   fmtDate(e,true))
  }
  const res = await request.post('kc/proDivide/getProDividePage', ps)
  const d   = res.data.data
  tableData.value = d.list || []
  total.value     = d.total || 0
  pageNo.value    = d.pageNo || p
}

// --- 重置 ---
function reset() {
  query.code = ''
  query.status = null
  query.dateRange = []
  fetchData(1)
}

// --- 打开审核弹窗 ---
function openAudit(row: ProDivide) {
  currentRow = row
  auditForm.code    = row.code
  auditForm.auditor = ''
  auditForm.pass    = null
  auditForm.comment = ''
  auditVisible.value = true
}

// --- 提交审核 & 生成出入库 ---
async function submitAudit() {
  await auditFormRef.value.validate()
  // 1) 调用审核接口
  await request.post('kc/proDivide/check', {
    code:       auditForm.code,
    typeId:     2,                // 拆卸类型
    status:     auditForm.pass? 2:3,
    checkManId: auditForm.auditor,
    checkComment: auditForm.comment,
    checkRes:   auditForm.pass
  })
  ElMessage.success('审核完成')
  auditVisible.value = false

  // // 2) 如果通过，则生成入/出库单
  // if (auditForm.pass && currentRow) {
  //   const rr = await request.get('kc/proDivide/getOneProDivide', { params:{ code: currentRow.code }})
  //   const data = rr.data.data as ProDivide
  //   const { outOrder, outDetails, inOrder, inDetails } = transformDataForDivide(data)

  //   // 产品出库
  //   await request.post('kc/outStore/addOutStore', outOrder)
  //   await Promise.all(outDetails.map(d => request.post('kc/outStoreDetail/addOutStoreDetail', d)))
  //   outDetails.forEach(d => {
  //     request.post('kc/StoreGoodSummary/method',{
  //       sid: d.storeId, gid: d.goodId, stock: -d.count, sumCost: d.outStoreSumCost
  //     })
  //   })
  //   request.post('workflowDesign/workFlow/startProcess',{ code: outOrder.code, type: 6 })

  //   // 原料入库
  //   await request.post('kc/inStore/addInStore', inOrder)
  //   await Promise.all(inDetails.map(d => request.post('kc/inStoreDetail/addInStoreDetail', d)))
  //   inDetails.forEach(d => {
  //     request.post('kc/StoreGoodSummary/method',{
  //       sid: d.storeId, gid: d.goodId, stock: d.count, sumCost: d.inStoreSumCost
  //     })
  //   })
  //   request.post('workflowDesign/workFlow/startProcess',{ code: inOrder.inStoreCode, type: 5 })

  //   ElMessage.success('生成出/入库单成功')
  // }

  fetchData(pageNo.value)
}

// // --- 转换函数：ProDivide → 出库单 & 入库单 ---
// /**
//  * 把 ProDivide 转成：
//  *  - 产品出库单头 + 明细 （bom.product）
//  *  - 原料入库单头 + 明细 （bom.material.slice(1...)）
//  */
// function transformDataForDivide(data: ProDivide) {
//   // --- 1. 产品出库 ---
//   const prod = data.bom.product
//   const prodCount = data.count
//   const outOrder: OutStoreOrder = {
//     id: 0,
//     code: data.code,
//     orderDate: new Date(data.date),
//     sourceCode: data.code,
//     cid: 0,
//     businessmanId: data.uid,
//     deptId: data.did,
//     orderStatus: 0,
//     storeManId: data.skid,
//     orderTypeId: 0,
//     typeId: 6,  // 拆卸时产品出库
//     outStoreSumPrice: 0,
//     createId: 0,
//     createDate: new Date(),
//     updateId: 0,
//     updateDate: new Date(),
//     isDelete: 0
//   }
//   const outDetails: outStoreDetail[] = [{
//     id: 0,
//     outStoreCode: data.code,
//     goodId: prod.id,
//     goodsCode: prod.code,
//     goodsName: prod.name,
//     tax: prod.tax || 0,
//     count: prodCount,
//     notes: '',
//     storeId: data.sids[0],      // 用第一个仓库
//     storeName: '',
//     unit: '',
//     singlePrice: prod.tax,
//     taxSinglePrice: prod.tax,
//     taxSumPrice: prod.tax * prodCount,
//     sumPrice: prod.tax * prodCount,
//     outStoreSingleCost: prod.tax,
//     outStoreSumCost: prod.tax * prodCount,
//     isDelete: 0,
//     createId: 0,
//     createDate: new Date(),
//     updateId: 0,
//     updateDate: new Date()
//   }]
//   outOrder.outStoreSumPrice = outDetails[0].outStoreSumCost

//   // --- 2. 原料入库 ---
//   const inOrder: InStoreOrder = {
//     id: 0,
//     inStoreCode: data.code,
//     goodId: 0,
//     goodsCode: '',
//     goodsName: '',
//     count: 0,
//     notes: '',
//     storeId: 0,
//     storeName: '',
//     taxSumPrice: 0,
//     sumPrice: 0,
//     inStoreSingleCost: 0,
//     inStoreSumCost: 0,
//     isDelete: 0,
//     createId: 0,
//     createDate: new Date(),
//     updateId: 0,
//     updateDate: new Date()
//   }
//   const inDetails: InStoreDetail[] = data.bom.material.slice(1).map((m, i) => {
//     const cnt = data.count
//     return {
//       id: 0,
//       inStoreCode: data.code,
//       goodId: m.id,
//       goodsCode: m.code,
//       goodsName: m.name,
//       count: cnt,
//       notes: '',
//       storeId: data.sids[i + 1] ?? data.sids[0],
//       storeName: '',
//       taxSumPrice: (m.tax || 0) * cnt,
//       sumPrice: (m.tax || 0) * cnt,
//       inStoreSingleCost: m.tax || 0,
//       inStoreSumCost: (m.tax || 0) * cnt,
//       isDelete: 0,
//       createId: 0,
//       createDate: new Date(),
//       updateId: 0,
//       updateDate: new Date()
//     }
//   })

  return { outOrder, outDetails, inOrder, inDetails }
}

</script>

<style scoped>
.mb-4 { margin-bottom: 16px }
</style>
